import sys, os,csv,datetime
from PyQt5 import  QtWidgets
from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog,
                             QAbstractItemView, QMessageBox, QDataWidgetMapper,
                             QTableView, QDialog)

from PyQt5.QtCore import (pyqtSlot, Qt, QItemSelectionModel,
                          QModelIndex, QUrl,QTimer)

from PyQt5.QtGui import QDesktopServices, QPalette, QColor, QIcon, QBrush,QTextCursor
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QComboBox, QLineEdit, QPushButton, QMessageBox, \
	QDesktopWidget

from eng_ui_MainWindow import Ui_MainWindow as Eng_UI
from ui_MainWindow import Ui_MainWindow as CH_UI
from AddDrawing import DrawingDialog as NewDrawing
from production_record import ProductionRecordDialog as PRDialog

from myDelegates import QmyComboBoxDelegate


# 用户管理界面----暂时就改密码的功能
class UserManage(QWidget):  # 登录页面
	def __init__(self, main_window, is_eng):
		super().__init__()
		self.main_window = main_window
		self.is_eng = is_eng
		self.setWindowIcon(QIcon('resources/mainico.png'))
		self.initUI()
	
	def initUI(self):
		para = 'setting' if self.is_eng else '设置'
		self.setWindowTitle(f'{para}')
		self.setGeometry(300, 300, 400, 300)
		self.setFixedSize(self.width(), self.height())  # 固定窗口大小
		self.setStyleSheet("""
            QWidget {
                background-color: #f0f0f0;
            }
            QLabel {
                font-size: 16px;
                color: #333;
                font-weight: bold;  /* 设置标签字体加粗 */
            }
            QComboBox {
                height: 30px;
                border: 1px solid #ccc;
                border-radius: 3px;
                padding-left: 5px;
                font-size: 16px;
                font-weight: bold;  /* 设置标签字体加粗 */
            }
            QLineEdit {
                height: 30px;
                border: 1px solid #ccc;
                border-radius: 3px;
                padding-left: 5px;
                background-color: white;
                font-size: 16px;
            }
            QPushButton {
                height: 35px;
                background-color: #007BFF;
                color: white;
                border: none;
                border-radius: 3px;
                font-size: 16px;
                font-weight: bold;  /* 设置按钮字体加粗 */
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """)
		
		layout = QVBoxLayout()
		layout.setSpacing(15)
		layout.setContentsMargins(50, 20, 50, 20)
		
		# 用户类型标签和下拉框
		para = 'user type:' if self.is_eng else '用户类型:'
		user_type_label = QLabel(f'{para}')
		self.user_type_combo = QComboBox()
		self.user_type_combo.addItems(['Admin', 'User', 'Eng', 'QC', 'Sales'])
		layout.addWidget(user_type_label)
		layout.addWidget(self.user_type_combo)
		
		# 密码标签和输入框
		para = 'new password:' if self.is_eng else '新密码:'
		pwd_label = QLabel(f'{para}')
		self.pwd_lineedit = QLineEdit()
		self.pwd_lineedit.setEchoMode(QLineEdit.Password)
		self.pwd_lineedit.returnPressed.connect(self.handle_pwd)
		layout.addWidget(pwd_label)
		layout.addWidget(self.pwd_lineedit)
		
		# 按钮
		para = 'modify the password' if self.is_eng else '修改密码'
		login_button = QPushButton(f'{para}')
		login_button.clicked.connect(self.handle_pwd)
		layout.addWidget(login_button)
		
		# 清空记录
		para = 'clear records' if self.is_eng else '清空记录'
		clear_button = QPushButton(f'{para}')
		clear_button.clicked.connect(self.clear_records)
		layout.addWidget(clear_button)
		
		# 设置销售图纸路径
		para = 'set sale drawing path' if self.is_eng else '设置销售图纸路径'
		sale_drawing_button = QPushButton(f'{para}')
		sale_drawing_button.clicked.connect(self.set_sale_drawing_path)
		layout.addWidget(sale_drawing_button)
		
		self.setLayout(layout)
		self.center()
	
	def center(self):
		qr = self.frameGeometry()
		cp = QDesktopWidget().availableGeometry().center()
		qr.moveCenter(cp)
		self.move(qr.topLeft())
	
	def handle_pwd(self):
		user_type = self.user_type_combo.currentText()
		new_password = self.pwd_lineedit.text()
		res = self.main_window.set_pwd(user_type, new_password)  # 正确密码
		# 修改密码成功与否
		para = 'modify the password' if self.is_eng else '修改密码'
		para_success = f'the modification successed' if self.is_eng else '密码修改成功'
		para_fail = f'the modification failed' if self.is_eng else '密码修改失败'
		if res:
			QMessageBox.information(self, f'{para}', f'{user_type} {para_success}')
			self.close()
		else:
			QMessageBox.warning(self, f'{para}', f'{user_type} {para_fail}')
		
	def clear_records(self):
		reply = QMessageBox.question(None, '确认清空', '请先导出备份', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
		if reply == QMessageBox.Yes:
			query = QSqlQuery(self.main_window.DB)
			# 清空
			query.exec('DELETE FROM mold')
			if not query.isActive():
				print('清空表失败:', query.lastError().text())
			else:
				print('表已成功清空')
				self.main_window.tabModel.submitAll()
	
	def set_sale_drawing_path(self):
		sale_drawing_path = self.main_window.get_relative_path()
		if sale_drawing_path:
			# 使用 SQL 语句更新检验数据目录
			query = QSqlQuery(self.main_window.DB)
			update_query = f"UPDATE checkDic SET sale_drawing_path = '{sale_drawing_path}' WHERE id = 1"
			if not query.exec(update_query):
				QMessageBox.warning(self, '销售图纸路径', f'销售图纸路径更新失败：{query.lastError().text()}')
			else:
				QMessageBox.information(self, '销售图纸路径', f'图纸路径更新成功 ！')


# 自定义一个子类来重写 data 方法
class CustomSqlTableModel(QSqlTableModel):
	def __init__(self, parent=None, db=None):
		super().__init__(parent, db)
	
	def data(self, index, role=Qt.DisplayRole):
		status_column = self.fieldIndex('模具状态')
		if role == Qt.BackgroundRole:
			status = super().data(self.index(index.row(), status_column))
			if status == '承认中' or status == 'under recognition':
				return QBrush(QColor(201, 253, 180))  # C9FDB4
			elif status == '报废' or status == 'out of use':
				return QBrush(QColor(255, 0, 0))  # 红色
			elif status == '待维修' or status == 'awaiting repair':
				return QBrush(QColor(255, 255, 0))  # 黄色
			elif status == '维修中' or status == 'under repair':
				return QBrush(QColor(255, 165, 0))  # 橙色
			elif status == '待验收' or status == 'awaiting acceptance':
				return QBrush(QColor(162, 210, 255))  #A2D2FF
			elif status == '转去马来':
				return QBrush(QColor(230, 210, 250))  # E6D2FA
			elif status == '' :  # 未指定  # or status == '正常' or status == 'normal'
				return QBrush(QColor(193, 252, 251))  # C1FCFB
		
		elif role == Qt.TextAlignmentRole:
			return Qt.AlignCenter  # 文字居中对齐
		return super().data(index, role)


class QmyMainWindow(QMainWindow):
	
	def __init__(self, parent=None, is_eng=False):
		super().__init__(parent)  # 调用父类构造函数，创建窗体
		self.is_eng = is_eng
		self.ui = Eng_UI() if self.is_eng else CH_UI()  # 创建UI对象
		self.ui.setupUi(self)  # 构造UI界面
		self.ui.UI_init()
		self.setWindowIcon(QIcon('resources/mainico.png'))
		# 设置背景颜色
		palette = QPalette()
		palette.setColor(QPalette.Background, QColor(173, 216, 230))
		self.setPalette(palette)
		self.setCentralWidget(self.ui.splitter)
		
		self.win_title = "JF Mold Management System"
		self.user_management = UserManage(self, self.is_eng)
		self.ip=f'192.168.53.158'
		# 打开数据库
		self.DB = QSqlDatabase.addDatabase("QSQLITE")  # 添加 SQLITE数据库驱动
		self.DB.setDatabaseName("resources/moldManagement.db3")  # 设置数据库名称
		# if self.DB.open():
		# 	self.get_pwd("QC")  # 获取密码
		##   tableView显示属性设置
		self.ui.tableView.setSelectionBehavior(QAbstractItemView.SelectItems)
		self.ui.tableView.setSelectionMode(QAbstractItemView.SingleSelection)
		self.ui.tableView.setAlternatingRowColors(False)
		self.ui.tableView.verticalHeader().setDefaultSectionSize(22)
		self.ui.tableView.horizontalHeader().setDefaultSectionSize(100)
		
		if self.DB.open():  # 打开数据库
			self.__openTable()  # 打开数据表
			
		# 获取最后更新的时间
		read_query = QSqlQuery()
		select_query = "SELECT last_update_datetime FROM checkDic WHERE id = 1"
		if read_query.exec(select_query):
			if read_query.next():
				self.last_update_datetime = read_query.value(0)
		
		self.last_update_datetime = f'最后更新的时间: {self.last_update_datetime}' if not self.is_eng \
							else  f'The last update time: {self.last_update_datetime}'
		
	
	# self.admin_mode()
	
	##  ==============自定义功能函数===========
	
	def admin_mode(self):
		'''啥都能干'''
		self.setWindowTitle(f'{self.win_title}--Admin               {self.last_update_datetime}')
		
		self.ui.actOpenDB.setEnabled(True)
		self.enable_add_and_delete(True)
		self.enable_mold_details(True)
		self.ui.actSubmit.setEnabled(True)
	
	def eng_mode(self):
		self.setWindowTitle(f'{self.win_title}--Eng               {self.last_update_datetime}')
		
		self.ui.actOpenDB.setEnabled(False)
		self.enable_add_and_delete(False)
		self.enable_mold_details(False)
		self.ui.actSubmit.setEnabled(True)
		
		self.ui.le_moldlocation.setEnabled(True)  # 模具存放位置
		self.ui.pte_status.setEnabled(True)  # 状况
		self.ui.pte_record.setEnabled(True)  # 维修记录
		self.ui.pte_memo.setEnabled(True)  # 备注
		self.ui.btn_production_record.setEnabled(True)  # 生产记录
		
		# 查看图纸
		self.ui.btn_tuzhi.setEnabled(True)
		self.ui.cbx_drawing.setEnabled(True)
		
		# 验收报告
		self.ui.btn_yanshou.setEnabled(True)
		# 产品检验数据
		self.ui.btn_product_check.setEnabled(True)
	
	def QC_mode(self):
		self.setWindowTitle(f'{self.win_title}--QC               {self.last_update_datetime}')
		
		self.ui.tableView.setEditTriggers(QTableView.NoEditTriggers)
		self.ui.actOpenDB.setEnabled(False)
		self.enable_add_and_delete(False)
		self.enable_mold_details(False)
		
		self.ui.btn_tuzhi.setEnabled(True)
		self.ui.cbx_drawing.setEnabled(True)
		
		self.ui.btn_yanshou.setEnabled(True)
		self.ui.btn_product_check.setEnabled(True)
	
	def user_mode(self):  # 控制user的一些操作
		'''只查看，不能编辑--后加：能够打开图纸和打开产品检验数据'''
		
		self.setWindowTitle(f'{self.win_title}--User               {self.last_update_datetime}')
		# 设置编辑触发条件为无，即禁止编辑
		self.ui.tableView.setEditTriggers(QTableView.NoEditTriggers)
		# 关闭act
		self.ui.actOpenDB.setEnabled(False)
		self.enable_add_and_delete(False)
		# 关闭模具细节
		self.enable_mold_details(False)
		# 打开图纸
		self.ui.cbx_drawing.setEnabled(True)
		self.ui.btn_tuzhi.setEnabled(True)
		# 打开产品检验数据
		self.ui.btn_product_check.setEnabled(True)
	
	def addbtn_sale_drawings(self):
		read_query = QSqlQuery(self.DB)
		select_query = "SELECT sale_drawing_path FROM checkDic WHERE id = 1"
		if read_query.exec(select_query):
			if read_query.next():
				sale_drawing_path = read_query.value(0)
				print(f'sale_drawing_path :{sale_drawing_path}')
				print(f'ip_path:{sale_drawing_path.replace("tfsm", self.ip)}')
				sale_drawing_path=sale_drawing_path.replace("tfsm", self.ip) if \
					 not os.path.exists(sale_drawing_path) else sale_drawing_path
				sale_drawing_path += f'/{self.ui.le_productname.text()}'
				print(sale_drawing_path)
				os.makedirs(sale_drawing_path, exist_ok=True)
				# 打开目录
				url = QUrl.fromLocalFile(sale_drawing_path)
				if not QDesktopServices.openUrl(url):
					QMessageBox.information(self, '提醒', f'还没有指定图纸目录')
			else:
				QMessageBox.warning(self, '图纸', '未找到对应的记录')
		else:
			QMessageBox.warning(self, '图纸', f'获取图纸目录失败：{read_query.lastError().text()}')
	
	def sales_mode(self):
		# 增加图纸按钮
		spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
		self.ui.horizontalLayout.addItem(spacerItem)
		para= f'drawings' if self.is_eng else f'图纸'
		btn_sale_drawing = QtWidgets.QPushButton(f'{para}', self.ui.groupBox_2)
		self.ui.horizontalLayout.addWidget(btn_sale_drawing)
		btn_sale_drawing.clicked.connect(self.addbtn_sale_drawings)
		btn_sale_drawing.setStyleSheet("""
		        		           QPushButton {
		        		               background-color: #00abff;
		        		               color: white;
		        		               border: none;
		        		               border-radius: 5px;
		        		               padding: 5px 10px;
		        		           }
		        		           QPushButton:hover {
		        		               background-color: #0012bc;
		        		           }
		        		       """)
		'''关闭细节部分'''
		self.setWindowTitle(f'{self.win_title}--Sales               {self.last_update_datetime}')
		self.ui.tableView.horizontalHeader().setDefaultSectionSize(120)
		# 设置编辑触发条件为无，即禁止编辑
		self.ui.tableView.setEditTriggers(QTableView.NoEditTriggers)
		# 关闭act
		self.ui.actOpenDB.setEnabled(False)
		self.enable_add_and_delete(False)
		# 关闭模具细节
		self.enable_mold_details(False)
		
		# 创建一个 QTimer 对象
		self.timer = QTimer(self)
		# 设置定时器的时间间隔，单位为毫秒
		self.timer.setInterval(1)
		# 将定时器的 timeout 信号连接到槽函数
		self.timer.timeout.connect(lambda: self.ui.splitter.setSizes([self.ui.splitter.width(), 0]))
		# 启动定时器
		self.timer.start()
		# 禁止分割条移动
		self.ui.splitter.setHandleWidth(0)
		self.ui.splitter.setOpaqueResize(False)
		
	
	def enable_add_and_delete(self, flag):
		# 禁止增删
		self.ui.actRecAppend.setEnabled(flag)
		self.ui.actRecDelete.setEnabled(flag)
		self.ui.actExport.setEnabled(flag)
		self.ui.actImport.setEnabled(flag)
		self.ui.actRecInsert.setEnabled(False)
	
	def enable_mold_details(self, flag):
		self.ui.btn_tuzhi.setEnabled(flag)
		self.ui.btn_addtuzhi.setEnabled(flag)
		self.ui.cbx_drawing.setEnabled(flag)
		self.ui.btn_deletetuzhi.setEnabled(flag)
		
		self.ui.btn_yanshou.setEnabled(flag)
		self.ui.btn_addyanshou.setEnabled(flag)
		
		self.ui.btn_product_check.setEnabled(flag)
		self.ui.btn_add_check.setEnabled(flag)
		
		self.ui.le_productname.setEnabled(flag)
		self.ui.le_moldtype.setEnabled(flag)
		self.ui.le_moldindex.setEnabled(flag)
		self.ui.le_moldlocation.setEnabled(flag)
		self.ui.dedit_accept.setEnabled(flag)
		self.ui.cbx_jixing.setEnabled(flag)
		self.ui.le_client.setEnabled(flag)
		self.ui.le_supplier.setEnabled(flag)
		self.ui.le_life.setEnabled(flag)
		self.ui.cbx_status.setEnabled(flag)
		
		self.ui.pte_status.setEnabled(flag)
		self.ui.pte_record.setEnabled(flag)
		self.ui.pte_memo.setEnabled(flag)  # 生产记录
		self.ui.btn_production_record.setEnabled(flag)
	
	def get_pwd(self, level):
		query = QSqlQuery(self.DB)
		query.prepare("SELECT pwd FROM userManage WHERE level = :level")  # 替换为实际表名
		query.bindValue(":level", level)
		
		if query.exec():
			if query.next():
				pwd = query.value(0)
				# print(f"{level}对应的密码是: {pwd}")
				return pwd  # 返回正确密码，与输入密码进行比较
			else:
				print(f"未找到level为 {level} 的记录")
		else:
			QMessageBox.critical(self, "查询错误", f"查询失败: {query.lastError().text()}")
	
	def set_pwd(self, level, new_pwd):
		query = QSqlQuery(self.DB)
		# 准备 SQL 更新语句
		query.prepare("UPDATE userManage SET pwd = :new_pwd WHERE level = :level")
		# 绑定新密码和 level 参数
		query.bindValue(":new_pwd", new_pwd)
		query.bindValue(":level", level)
		
		if query.exec():
			if query.numRowsAffected() > 0:
				print(f"成功更新 level 为 {level} 的密码")
				return True
			else:
				print(f"未找到 level 为 {level} 的记录，未进行更新")
				return False
		else:
			QMessageBox.critical(self, "更新错误", f"更新失败: {query.lastError().text()}")
			return False
	
	def __getFieldNames(self):  ##获取所有字段名称
		emptyRec = self.tabModel.record()  # 获取空记录，只有字段名
		self.fldNum = {}  # 字段名与序号的字典
		for i in range(emptyRec.count()):
			fieldName = emptyRec.fieldName(i)
			# self.ui.comboFields.addItem(fieldName)
			self.fldNum.setdefault(fieldName)
			self.fldNum[fieldName] = i
		print(self.fldNum)
	
	def __openTable(self):  ##打开数据表
		self.tabModel = CustomSqlTableModel(self, self.DB)  # 数据模型
		self.tabModel.setTable("mold")  # 设置数据表
		self.tabModel.setEditStrategy(QSqlTableModel.OnManualSubmit)  # 数据保存方式，OnManualSubmit , OnRowChange
		# self.tabModel.setSort(self.tabModel.fieldIndex("模具id"), Qt.AscendingOrder)  # 排序
		
		if (self.tabModel.select() == False):  # 查询数据失败
			QMessageBox.critical(self, "错误信息",
			                     "打开数据表错误,错误信息\n" + self.tabModel.lastError().text())
			return
		self.__getFieldNames()  # 获取字段名和序号
		
		# 设置状态栏
		para = ' the current total number of molds: ' if self.is_eng else ' 当前模具总数：'
		self.ui.status_label.setText(f"{para}{self.tabModel.rowCount()}   ")
		
		# 字段显示名
		if self.is_eng:
			self.tabModel.setHeaderData(self.fldNum["模具id"], Qt.Horizontal, "mold_code")
			self.tabModel.setHeaderData(self.fldNum["产品型号"], Qt.Horizontal, "product_type")
			self.tabModel.setHeaderData(self.fldNum["模号"], Qt.Horizontal, "mold_number")
			self.tabModel.setHeaderData(self.fldNum["模具类型"], Qt.Horizontal, "mold_type")
			self.tabModel.setHeaderData(self.fldNum["客户"], Qt.Horizontal, "client")
		else:
			self.tabModel.setHeaderData(self.fldNum["模具id"], Qt.Horizontal, "模具代号")
			self.tabModel.setHeaderData(self.fldNum["产品型号"], Qt.Horizontal, "产品型号")
			self.tabModel.setHeaderData(self.fldNum["模号"], Qt.Horizontal, "模号")
			self.tabModel.setHeaderData(self.fldNum["模具类型"], Qt.Horizontal, "模具类型")
			self.tabModel.setHeaderData(self.fldNum["客户"], Qt.Horizontal, "客户")
		
		self.tabModel.setHeaderData(self.fldNum["A0_min"], Qt.Horizontal, "A0_min")
		self.tabModel.setHeaderData(self.fldNum["A0_max"], Qt.Horizontal, "A0_max")
		self.tabModel.setHeaderData(self.fldNum["B0_max"], Qt.Horizontal, "B0_max")
		self.tabModel.setHeaderData(self.fldNum["B0_min"], Qt.Horizontal, "B0_min")
		self.tabModel.setHeaderData(self.fldNum["K0_min"], Qt.Horizontal, "K0_min")
		self.tabModel.setHeaderData(self.fldNum["K0_max"], Qt.Horizontal, "K0_max")
		self.tabModel.setHeaderData(self.fldNum["W_min"], Qt.Horizontal, "W_min")
		self.tabModel.setHeaderData(self.fldNum["W_max"], Qt.Horizontal, "W_max")
		self.tabModel.setHeaderData(self.fldNum["P1_min"], Qt.Horizontal, "P1_min")
		self.tabModel.setHeaderData(self.fldNum["P1_max"], Qt.Horizontal, "P1_max")
		# 以下字段不在tableView中显示
		self.tabModel.setHeaderData(self.fldNum["模具类型"], Qt.Horizontal, "模具类型")
		self.tabModel.setHeaderData(self.fldNum["机型"], Qt.Horizontal, "机型")
		self.tabModel.setHeaderData(self.fldNum["供应商"], Qt.Horizontal, "供应商")
		self.tabModel.setHeaderData(self.fldNum["接收日期"], Qt.Horizontal, "接收日期")
		self.tabModel.setHeaderData(self.fldNum["模具状况"], Qt.Horizontal, "模具状况")
		self.tabModel.setHeaderData(self.fldNum['模具寿命'], Qt.Horizontal, "模具寿命")
		self.tabModel.setHeaderData(self.fldNum["模具维修记录"], Qt.Horizontal, "模具维修记录")
		self.tabModel.setHeaderData(self.fldNum["备注"], Qt.Horizontal, "备注")
		self.tabModel.setHeaderData(self.fldNum["模具状态"], Qt.Horizontal, "模具状态")
		
		##创建界面组件与数据模型的字段之间的数据映射
		self.mapper = QDataWidgetMapper()
		self.mapper.setModel(self.tabModel)  # 设置数据模型
		self.mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit)
		
		##界面组件与tabModel的具体字段之间的联系
		self.mapper.addMapping(self.ui.le_productname, self.fldNum["产品型号"])
		self.mapper.addMapping(self.ui.le_moldindex, self.fldNum["模号"])
		self.mapper.addMapping(self.ui.le_client, self.fldNum["客户"])
		self.mapper.addMapping(self.ui.le_moldtype, self.fldNum["模具类型"])
		self.mapper.addMapping(self.ui.cbx_jixing, self.fldNum["机型"])
		self.mapper.addMapping(self.ui.le_supplier, self.fldNum["供应商"])
		self.mapper.addMapping(self.ui.dedit_accept, self.fldNum["接收日期"])
		self.mapper.addMapping(self.ui.pte_status, self.fldNum["模具状况"])
		self.mapper.addMapping(self.ui.pte_record, self.fldNum["模具维修记录"])
		self.mapper.addMapping(self.ui.pte_memo, self.fldNum["备注"])
		self.mapper.addMapping(self.ui.le_life, self.fldNum["模具寿命"])
		self.mapper.addMapping(self.ui.le_moldlocation, self.fldNum["模具存放位置"])
		self.mapper.addMapping(self.ui.cbx_status, self.fldNum["模具状态"])
		
		self.mapper.toFirst()  # 移动到首记录
		
		self.selModel = QItemSelectionModel(self.tabModel)  # 选择模型
		self.selModel.currentChanged.connect(self.do_currentChanged)  # 当前项变化时触发
		self.selModel.currentRowChanged.connect(self.do_currentRowChanged)  # 选择行变化时
		self.ui.tableView.setModel(self.tabModel)  # 设置数据模型
		self.ui.tableView.setSelectionModel(self.selModel)  # 设置选择模型
		
		# self.ui.tableView.setColumnHidden(self.fldNum["模具类型"], True)  # 隐藏列
		self.ui.tableView.setColumnHidden(self.fldNum["机型"], True)  # 隐藏列
		self.ui.tableView.setColumnHidden(self.fldNum["供应商"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["接收日期"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["模具状况"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["模具维修记录"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["备注"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["模具寿命"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["验收报告"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["模具存放位置"], True)
		self.ui.tableView.setColumnHidden(self.fldNum["模具状态"], True)
		
		# tableView上为"机型"字段设置自定义代理组件
		strList = ("CTM", "TCTM", "PTT", "平板机")
		self.__delegateDepart = QmyComboBoxDelegate()
		self.__delegateDepart.setItems(strList, True)
		self.ui.tableView.setItemDelegateForColumn(self.fldNum["机型"], self.__delegateDepart)
		## tableView上为"模具状态"字段设置自定义代理组件
		strList1 = ("正常", "维修中", "待维修", "报废", "待验收", "承认中", "转去马来")
		self.__delegateDepart1 = QmyComboBoxDelegate()
		self.__delegateDepart1.setItems(strList1, True)
		self.ui.tableView.setItemDelegateForColumn(self.fldNum["模具状态"], self.__delegateDepart1)
	
	def reorder_records(self):
		# 重新编号模具 id
		row_count = self.tabModel.rowCount()
		mold_id_column = self.tabModel.fieldIndex("模具id")
		for row in range(row_count):
			index = self.tabModel.index(row, mold_id_column)
			self.tabModel.setData(index, row + 1)
		# 提交重新编号的更改到数据库
		self.tabModel.submitAll()
	
	def get_relative_path(self):
		original_path = f"//tfsm/Eng/" if os.path.exists(f"//tfsm/Eng/") else f"//{self.ip}/Eng/"
		initial_dir = original_path if os.path.exists(original_path) else f""
		file_path = QFileDialog.getExistingDirectory(self, '选择文件夹', initial_dir)
		return file_path
	
	def get_all_drawing_code(self):
		check_query = QSqlQuery()
		check_query.prepare("SELECT drawing_code FROM drawings ")
		if check_query.exec_():
			existing_drawings = []
			while check_query.next():
				existing_drawings.append(check_query.value(0))
			return existing_drawings
	
	##  ==========由connectSlotsByName() 自动连接的槽函数==================
	@pyqtSlot()  ## 用户管理模块
	def on_actOpenDB_triggered(self):
		self.user_management.show()
		
	@pyqtSlot() # 导出
	def on_actExport_triggered(self):
		file_dialog = QFileDialog()
		file_path, _ = file_dialog.getSaveFileName(self, "保存 CSV 文件", "", "CSV Files (*.csv)")
		if file_path:
			try:
				# output_file= './resources/mold.csv'
				with open(file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
					writer = csv.writer(csvfile)
					
					# 获取列名
					query = QSqlQuery(f"PRAGMA table_info(mold);")
					column_names = []
					while query.next():
						column_names.append(query.value(1))
					writer.writerow(column_names)
					
					# 获取数据
					select_query = QSqlQuery(f"SELECT * FROM mold")
					while select_query.next():
						row = []
						for i in range(len(column_names)):
							value = select_query.value(i)
							if i == 0:
								row.append(f"{value}")
								print(value)
							else:
								row.append(value)
						writer.writerow(row)
				print(f"数据已成功导出到 {file_path}")
			except Exception as e:
				print(f"导出数据时出错: {e}")
	
	@pyqtSlot()  # 导入
	def on_actImport_triggered(self):
		# res=QMessageBox.question(None,'提醒','是否已经导出备份？')
		# if res == QDialog.Accepted:
		file_dialog = QFileDialog()
		file_path, _ = file_dialog.getOpenFileName(self, "选择 CSV 文件", "", "CSV Files (*.csv)")
		if file_path:
			try:
				# input_file='./resources/mold.csv'
				with open(file_path, 'r', encoding='utf-8-sig') as csvfile:
					reader = csv.reader(csvfile)
					column_names = next(reader)  # 获取表头
					
					placeholders = ', '.join(['?' for _ in column_names])
					insert_query_str = f"INSERT INTO mold ({', '.join(column_names)}) VALUES ({placeholders});"
					
					for row in reader:
						query = QSqlQuery()
						query.prepare(insert_query_str)
						for value in row:
							query.addBindValue(value)
						if not query.exec_():
							print(f"插入数据出错: {row}, 错误信息: {query.lastError().text()}")
				self.tabModel.select()  # 刷新一下
				# 更新状态栏
				para = f"  the current total number of molds: {self.tabModel.rowCount()}" if self.is_eng else f" 当前模具总数：{self.tabModel.rowCount()}"
				self.ui.status_label.setText(f'{para}')
				print(f"数据已成功从 {file_path} 导入")
			except Exception as e:
				print(f"导入数据时出错: {e}")
	
	@pyqtSlot()  ##保存修改
	def on_actSubmit_triggered(self):
		res = self.tabModel.submitAll()
		if (res == False):
			QMessageBox.information(self, "消息",
			                        "数据保存错误,错误信息\n" + self.tabModel.lastError().text())
		else:
			# self.ui.actSubmit.setEnabled(False)
			self.ui.actRevert.setEnabled(False)
			
			# 更新状态栏
			para = f"  the current total number of molds: {self.tabModel.rowCount()}" if self.is_eng else f" 当前模具总数：{self.tabModel.rowCount()}"
			self.ui.status_label.setText(f'{para}')
			
			# 更新最后修改时间
			last_update_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
			# 使用 SQL 语句更新检验数据目录
			query = QSqlQuery()
			update_query = f"UPDATE checkDic SET last_update_datetime = '{last_update_datetime}' WHERE id = 1"
			query.exec(update_query)
			
	
	@pyqtSlot()  ##取消修改
	def on_actRevert_triggered(self):
		self.tabModel.revertAll()
		self.ui.actSubmit.setEnabled(False)
		self.ui.actRevert.setEnabled(False)
	
	@pyqtSlot()  ##添加记录
	def on_actRecAppend_triggered(self):
		self.tabModel.insertRow(self.tabModel.rowCount(), QModelIndex())  # 在末尾添加一个记录
		curIndex = self.tabModel.index(self.tabModel.rowCount() - 1, 1)  # 创建最后一行的ModelIndex
		self.selModel.clearSelection()  # 清空选择项
		self.selModel.setCurrentIndex(curIndex, QItemSelectionModel.Select)  # 设置刚插入的行为当前选择行
	
	@pyqtSlot()  ##插入记录
	def on_actRecInsert_triggered(self):
		curIndex = self.ui.tableView.currentIndex()  # QModelIndex
		self.tabModel.insertRow(curIndex.row(), QModelIndex())
		self.selModel.clearSelection()  # 清除已有选择
		self.selModel.setCurrentIndex(curIndex, QItemSelectionModel.Select)
	
	@pyqtSlot()  ##删除记录
	def on_actRecDelete_triggered(self):
		curIndex = self.selModel.currentIndex()  # 获取当前选择单元格的模型索引
		self.tabModel.removeRow(curIndex.row())  # 删除当前行
		
		# 删除关联图纸的记录
		mold_code_index = self.tabModel.index(curIndex.row(), 0)  # 模具代号
		mold_code = self.tabModel.data(mold_code_index)  # 获取模具代号
		delete_query = QSqlQuery()
		delete_query.prepare("DELETE FROM relation WHERE  mold = :mold_code")
		delete_query.bindValue(':mold_code', mold_code)
		if delete_query.exec_():
			if delete_query.numRowsAffected() > 0:
				print("关联记录删除成功")
			else:
				print("未找到对应的关联记录，删除失败")
		else:
			print(f"关联记录删除失败: {delete_query.lastError().text()}")
		
		# 删除生产记录表
		table_name = f"production_record_{mold_code}"
		delete_query = QSqlQuery()
		delete_query.prepare(f"DROP TABLE IF EXISTS {table_name} ")
		if delete_query.exec_():
			print(f"{table_name} 删除成功")
		else:
			print(f"{table_name} 删除失败: {delete_query.lastError().text()}")
	
	@pyqtSlot()
	def on_btn_check_clicked(self):
		con_product_name = self.ui.le_com_productname.text().upper()
		con1 = f"产品型号 LIKE '%{con_product_name}%'" if con_product_name else f""
		
		con_jixing = self.ui.cbox_jixing.currentText()
		con2 = f"" if con_jixing == "ALL" else f"机型='{con_jixing}'"
		
		allow_bias = self.ui.dsb_delt.value()
		A0_ref = self.ui.dsb_A0.value()
		con3 = f"A0_min <= {A0_ref}+{allow_bias} AND A0_max >= {A0_ref}-{allow_bias} " if A0_ref != 0 else f""
		B0_ref = self.ui.dsb_B0.value()
		con4 = f"B0_min <= {B0_ref}+{allow_bias}  AND B0_max >= {B0_ref}-{allow_bias}" if B0_ref != 0 else f""
		K0_ref = self.ui.dsb_K0.value()
		con5 = f"K0_min <= {K0_ref}+{allow_bias}  AND K0_max >= {K0_ref}-{allow_bias}" if K0_ref != 0 else f""
		
		mold_code = self.ui.le_mold_code.text()
		drawing_code = self.ui.le_drawing_code.text()
		
		conditions = []
		if con1:
			conditions.append(con1)
		if con2:
			conditions.append(con2)
		if con3:
			conditions.append(con3)
		if con4:
			conditions.append(con4)
		if con5:
			conditions.append(con5)
		
		if mold_code:  # 仅根据模具代号搜索
			con6 = f"模具id LIKE '%{mold_code}%'" if mold_code else f""
			self.tabModel.setFilter(con6)
			print(con6)
		elif drawing_code:  # 根据图纸搜索
			check_query = QSqlQuery()
			check_query.prepare("SELECT mold FROM relation WHERE drawing = :drawing_code")
			check_query.bindValue(':drawing_code', drawing_code)
			if check_query.exec_():
				mold_list = []
				while check_query.next():
					# 获取模具信息
					mold_info = check_query.value(0)  # 获取模具信息
					mold_list.append(mold_info)
				mold_str = ', '.join([f"'{value}'" for value in mold_list])
				con7 = f"模具id IN ({mold_str})"
				self.tabModel.setFilter(con7)
				print(con7)
		elif conditions:
			con = " AND ".join(conditions)
			print(con)
			if con:
				self.tabModel.setFilter(con)
				# 排序按照A0_min,B0_min,k0_min多级排序
				self.tabModel.setQuery(
					QSqlQuery(f"SELECT * FROM mold WHERE {con} ORDER BY A0_min DESC,B0_min DESC,K0_min DESC"))
		else:
			self.tabModel.setFilter(f'')
	
	@pyqtSlot()
	def on_btn_addtuzhi_clicked(self):
		'''在drawings中新增记录，并相互关联，更新图纸的下拉列表'''
		# 创建新建记录对话框
		existing_drawings = self.get_all_drawing_code()
		new_drawing_dialog = NewDrawing(existing_drawings, self.is_eng)
		new_drawing_dialog.signal_delete_drawing.connect(self.delete_drawing)  # 删除图纸记录
		if new_drawing_dialog.exec_() == QDialog.Accepted:
			drawing_code = new_drawing_dialog.drawing_id_input.text()
			client = new_drawing_dialog.customer_input.text()
			drawing_path = new_drawing_dialog.drawing_path_input.text()
			print(f'图纸代号: {drawing_code}')
			print(f'客户: {client}')
			print(f'图纸路径: {drawing_path}')
			
			# 获取当前所选模具代号和相关图纸
			mold_code = None
			selected_indexes = self.ui.tableView.selectedIndexes()
			if selected_indexes:
				mold_code_index = self.tabModel.index(selected_indexes[0].row(), 0)  # 模具代号
				mold_code = self.tabModel.data(mold_code_index)  # 获取模具代号
				print(f"当前模具代号为：{mold_code}")
			
			# # 判断是否已经有图纸记录，若有则更建立联系
			# 检查图纸数据库中是否存在该图纸代号
			check_query = QSqlQuery()
			check_query.prepare("SELECT drawing_path FROM drawings WHERE drawing_code = :drawing_code")
			check_query.bindValue(':drawing_code', drawing_code)
			if check_query.exec_():
				if check_query.next():  # 已经存在该图纸
					original_path = check_query.value(0)  # 原始的路径
					if drawing_path and drawing_path not in [original_path,original_path.replace("tfsm", self.ip)]:  # 更新图纸路径的条件
						update_query = QSqlQuery()
						update_query.prepare(
							"UPDATE drawings SET drawing_path = :drawing_path WHERE drawing_code = :drawing_code")
						update_query.bindValue(':drawing_path', drawing_path)
						update_query.bindValue(':drawing_code', drawing_code)
						update_query.exec_()
				
				else:  # 不存在该图纸代号，需要插入新记录
					
					if not drawing_path:  # 如果没有新图纸，则不添加
						QMessageBox.information(self, '提醒', f'尚未添加该图纸')
						return
					insert_query = QSqlQuery()
					insert_query.prepare(
						"INSERT INTO drawings (drawing_code, client, drawing_path) "
						"VALUES (:drawing_code, :client, :path)")
					
					insert_query.bindValue(':drawing_code', drawing_code)
					insert_query.bindValue(':client', client)
					insert_query.bindValue(':path', drawing_path)
					if insert_query.exec_():
						print("新记录插入成功")
					else:
						print(f"新记录插入失败: {insert_query.lastError().text()}")
			
			# 建立联系
			self.add_association(mold_code, drawing_code)
			# 添加进下拉选项
			self.ui.cbx_drawing.addItem(drawing_code)
	
	# 增加关联记录
	def add_association(self, mold_id, drawing_id):
		insert_query = QSqlQuery()
		insert_query.prepare("INSERT INTO relation (mold, drawing) VALUES (:mold_id, :drawing_id)")
		insert_query.bindValue(':mold_id', mold_id)
		insert_query.bindValue(':drawing_id', drawing_id)
		if insert_query.exec_():
			print("关联记录添加成功")
			self.ui.btn_deletetuzhi
		else:
			print(f"关联记录添加失败: {insert_query.lastError().text()}")
	
	# 删除关联记录
	def delete_association(self, mold_id, drawing_id):
		delete_query = QSqlQuery()
		delete_query.prepare("DELETE FROM relation WHERE mold = :mold_id AND drawing = :drawing_id")
		delete_query.bindValue(':mold_id', mold_id)
		delete_query.bindValue(':drawing_id', drawing_id)
		if delete_query.exec_():
			if delete_query.numRowsAffected() > 0:
				print("关联记录删除成功")
			else:
				print("未找到对应的关联记录，删除失败")
		else:
			print(f"关联记录删除失败: {delete_query.lastError().text()}")
	
	# 删除图纸记录
	def delete_drawing(self, drawing_code):
		print(drawing_code)
		delete_query = QSqlQuery()
		delete_query.prepare("DELETE FROM drawings WHERE drawing_code = :drawing_code")
		delete_query.bindValue(':drawing_code', drawing_code)
		if delete_query.exec_():
			if delete_query.numRowsAffected() > 0:
				print("图纸记录删除成功")
			else:
				print("未找到对应的图纸记录，删除失败")
		else:
			print(f"图纸记录删除失败: {delete_query.lastError().text()}")
		
		# 删除所有关联
		delete_query = QSqlQuery()
		delete_query.prepare("DELETE FROM relation WHERE  drawing = :drawing_code")
		delete_query.bindValue(':drawing_code', drawing_code)
		if delete_query.exec_():
			if delete_query.numRowsAffected() > 0:
				print("关联记录删除成功")
			else:
				print("未找到对应的关联记录，删除失败")
		else:
			print(f"关联记录删除失败: {delete_query.lastError().text()}")
	
	@pyqtSlot()
	def on_btn_tuzhi_clicked(self):
		drawing_code = self.ui.cbx_drawing.currentText().split('|')[0]
		check_query = QSqlQuery()  # 根据下拉列表所选图纸的代号来打开对于的目录
		check_query.prepare("SELECT drawing_path FROM drawings WHERE drawing_code = :drawing_code")
		check_query.bindValue(':drawing_code', drawing_code)
		if check_query.exec_():
			if check_query.next():
				drawing_path = check_query.value(0)
				if not os.path.exists(drawing_path):
					drawing_path=drawing_path.replace("tfsm", self.ip)
				try:
					# 打开目录
					url = QUrl.fromLocalFile(drawing_path)
					if not QDesktopServices.openUrl(url):
						QMessageBox.information(self, '提醒', f'没有权限')
				except OSError as e:
					QMessageBox.warning(self, '打开图纸目录', f'错误码：{e}')
	
	@pyqtSlot()
	def on_btn_deletetuzhi_clicked(self):
		res = QMessageBox.question(self, '提醒', '是否确定取消关联', QMessageBox.Yes | QMessageBox.No)
		if res == QMessageBox.Yes:
			drawing_code = self.ui.cbx_drawing.currentText().split('|')[0]
			mold_code = None
			selected_indexes = self.ui.tableView.selectedIndexes()
			if selected_indexes:
				mold_code_index = self.tabModel.index(selected_indexes[0].row(), 0)  # 模具代号
				mold_code = self.tabModel.data(mold_code_index)  # 获取模具代号
			if drawing_code:  # 选中才会取消关联，移出下拉列表
				# 取消关联
				self.delete_association(mold_code, drawing_code)
				# 移除下拉框
				self.ui.cbx_drawing.removeItem(self.ui.cbx_drawing.currentIndex())
	
	@pyqtSlot()
	def on_btn_addyanshou_clicked(self):
		'''绑定验收报告，现在暂时是一个模具添加一个'''
		selected_indexes = self.ui.tableView.selectedIndexes()
		if selected_indexes:
			try:
				mold_id_index = self.tabModel.index(selected_indexes[0].row(), 0)  # 模具id index
				mold_id = self.tabModel.data(mold_id_index)
				yanshou_report_path = self.get_relative_path()  # 获取验收报告目录
				print(f"模具id: {mold_id},  验收报告目录：{yanshou_report_path}")
				if yanshou_report_path:
					# 使用 SQL 语句更新数据库
					query = QSqlQuery()
					update_query = f"UPDATE mold SET 验收报告 = '{yanshou_report_path}' WHERE 模具id = {mold_id}"
					if not query.exec(update_query):
						QMessageBox.warning(self, '模具验收报告', f'模具验收报告绑定失败：{query.lastError().text()}')
					else:
						curIndex = self.ui.tableView.currentIndex()
						# 刷新表格视图
						self.tabModel.select()
						self.selModel.setCurrentIndex(curIndex, QItemSelectionModel.Select)
						if yanshou_report_path:
							QMessageBox.information(self, '模具验收报告', f'模具验收报告绑定成功 ！')
			except OSError as e:
				QMessageBox.warning(self, '模具验收报告', f'模具验收报告绑定失败：{e}')
	
	@pyqtSlot()
	def on_btn_yanshou_clicked(self):
		selected_indexes = self.ui.tableView.selectedIndexes()
		if selected_indexes:
			# 验收报告在第 23 列(索引为 22)
			yanshou_category_index = self.tabModel.index(selected_indexes[0].row(), 21)
			yanshou_category = self.tabModel.data(yanshou_category_index)
			if not os.path.exists(yanshou_category):
				yanshou_category=yanshou_category.replace("tfsm", self.ip)
			# print(yanshou_category)
			try:
				# 打开目录
				url = QUrl.fromLocalFile(yanshou_category)
				if not QDesktopServices.openUrl(url):
					QMessageBox.information(self, '提醒', f'还没有绑定模具验收报告目录')
			# 刷新表格视图
			# self.tabModel.select()
			except OSError as e:
				QMessageBox.warning(self, '打开验收报告目录', f'验收报告目录打开失败：{e}')
	
	@pyqtSlot()
	def on_btn_product_check_clicked(self):
		# 读取产品检验数据目录
		read_query = QSqlQuery()
		select_query = "SELECT check_dic FROM checkDic WHERE id = 1"
		if read_query.exec(select_query):
			if read_query.next():
				retrieved_directory = read_query.value(0)
				if not os.path.exists(retrieved_directory):
					retrieved_directory=retrieved_directory.replace("tfsm", self.ip)
				# QMessageBox.information(self, '产品检验数据', f'读取到的产品检验数据目录为: {retrieved_directory}')
				# 打开目录
				url = QUrl.fromLocalFile(retrieved_directory)
				if not QDesktopServices.openUrl(url):
					QMessageBox.information(self, '提醒', f'还没有绑定产品检测数据目录')
			else:
				QMessageBox.warning(self, '产品检验数据', '未找到对应的记录')
		else:
			QMessageBox.warning(self, '产品检验数据', f'读取产品检验数据目录失败：{read_query.lastError().text()}')
	
	@pyqtSlot()
	def on_btn_add_check_clicked(self):
		# 设定检验数据的目录
		check_category = self.get_relative_path()
		if check_category:
			# 使用 SQL 语句更新检验数据目录
			query = QSqlQuery()
			update_query = f"UPDATE checkDic SET check_dic = '{check_category}' WHERE id = 1"
			if not query.exec(update_query):
				QMessageBox.warning(self, '产品检验数据', f'产品检验数据目录更新失败：{query.lastError().text()}')
			else:
				QMessageBox.information(self, '产品检验数据', f'产品检验数据目录更新成功 ！')
	
	@pyqtSlot()
	def on_btn_return_clicked(self):
		self.tabModel.setFilter(f"")
		self.ui.le_mold_code.setText(f"")
		self.ui.le_drawing_code.setText(f"")
		self.ui.le_com_productname.setText("")
		self.ui.cbox_jixing.setCurrentIndex(0)
		self.ui.dsb_A0.setValue(0)
		self.ui.dsb_B0.setValue(0)
		self.ui.dsb_K0.setValue(0)
		self.ui.dsb_delt.setValue(0)
	
	@pyqtSlot()
	def on_btn_production_record_clicked(self):
		selected_indexes = self.ui.tableView.selectedIndexes()
		if selected_indexes:
			mold_code_index = self.tabModel.index(selected_indexes[0].row(), 0)  # 模具代号
			mold_code = self.tabModel.data(mold_code_index)  # 获取模具代号
		else:
			return
		# 生产记录表的表名
		table_name = f"production_record_{mold_code}"
		# print(f'表名：{table_name}')
		# 创建表
		query = QSqlQuery(self.DB)
		# 创建生产记录表
		# 创建生产记录表
		if not query.exec_(f'''
		      CREATE TABLE IF NOT EXISTS {table_name} (
		          id INTEGER PRIMARY KEY AUTOINCREMENT,
		          start_date TEXT,
		          end_date TEXT,
		          machine TEXT,
		          production_length REAL
		      )
		  '''):
			print(f"{table_name}创建失败: {query.lastError().text()}")
		else:
			print(f'{table_name}创建成功')
		
		str_mold_life = self.ui.le_life.text()
		mold_life = int(str_mold_life) if str_mold_life else 0
		pr = PRDialog(self.DB, table_name, mold_life, self.is_eng)
		if pr.exec_() == QDialog.Accepted:
			original_text = self.ui.pte_memo.toPlainText()
			if original_text:   # 已经有信息了，前两行必定时total_output和rest_lifespan
				original_text_list=original_text.split('\n')
				if '总产量' in original_text_list[0] and '剩余寿命' in original_text_list[1]:
					original_text = '\n'.join(original_text_list[3:])
					
			print(f'=={original_text}==')

			total_output,rest_lifespan = pr.production_res.split('    ')
			para='Note below if necessary' if self.is_eng else '可在下方备注'
			self.ui.pte_memo.setPlainText(f'{total_output}\n{rest_lifespan}\n**{para}**\n{original_text}')
			# 获取文本光标
			cursor = self.ui.pte_memo.textCursor()
			# 将光标移动到文档末尾
			cursor.movePosition(QTextCursor.End)
			# 设置光标到文本编辑器
			self.ui.pte_memo.setTextCursor(cursor)
			# 设置焦点到文本编辑器
			self.ui.pte_memo.setFocus()
			
	##  =============自定义槽函数===============================
	def do_currentChanged(self, current, previous):  ##更新actPost和actCancel 的状态
		self.ui.actSubmit.setEnabled(self.tabModel.isDirty())  # 有未保存修改时可用
		self.ui.actRevert.setEnabled(self.tabModel.isDirty())
	
	def do_currentRowChanged(self, current, previous):  # 行切换时的状态控制
		# self.ui.actRecDelete.setEnabled(current.isValid())
		self.mapper.setCurrentIndex(current.row())  # 更新数据映射的行号
		# 更新图纸下拉框选项
		drawing_list = []  # 图纸列表
		# 直接使用 current 获取当前行的模具代号
		if current.isValid():
			mold_code_index = self.tabModel.index(current.row(), 0)  # 模具代号
			mold_code = self.tabModel.data(mold_code_index)  # 获取模具代号
			
			check_query = QSqlQuery()
			check_query.prepare("SELECT drawing FROM relation WHERE mold = :mold_code")
			check_query.bindValue(':mold_code', mold_code)
			if check_query.exec_():
				while check_query.next():
					# 获取相关图纸信息
					drawing_info = check_query.value(0)  # 获取图纸信息
					drawing_list.append(drawing_info)
			
			# 获取图纸对应的供应商
			for i in range(len(drawing_list)):
				check_query = QSqlQuery()
				check_query.prepare("SELECT client FROM drawings WHERE drawing_code = :drawing_code")
				check_query.bindValue(':drawing_code', drawing_list[i])
				if check_query.exec_():
					check_query.next()
					# 获取相关图纸信息
					client_info = check_query.value(0)  # 获取图纸信息
					drawing_list[i] += f'|{client_info}'
			# 清空下拉框原有的选项
			self.ui.cbx_drawing.clear()
			# 将图纸列表添加进图纸下拉框
			self.ui.cbx_drawing.addItems(drawing_list)

##  ============窗体测试程序 ================================
if __name__ == "__main__":  # 用于当前窗体测试
	app = QApplication(sys.argv)  # 创建GUI应用程序
	form = QmyMainWindow()  # 创建窗体
	form.show()
	sys.exit(app.exec_())
